const { sqlite3 } = require('../../mysql')


// 获取漫画列表
const verList = async (ctx) => {
  console.log('ctx.query:', ctx.query)
  let formData = ctx.query
  let offset = (formData.currentPage - 1) * formData.pageSize
  let limit = formData.pageSize
  let keyword = formData.title
  if (keyword) {
    data = await sqlite3('version')
      .where('title', 'LIKE', '%' + keyword + '%')
      .orderBy('id', 'desc')
      .select()
      .limit(formData.limit)
      .offset(offset)
    total = data.length
  } else {
    limitdata = await sqlite3('version').count({ total: '*' })
    data = await sqlite3('version').orderBy('id', 'asc').select().limit(limit).offset(offset)
    total = limitdata[0].total
    console.log('pageSize:', formData.currentPage, 'currentPage:', limit)
  }
  if (data) {
    ctx.body = {
      success: true,
      data: {
        list: data,
        total,
        pageSize: Number(limit),
        currentPage: Number(formData.currentPage)
      },
    }
  } else {
    ctx.body = {
      success: false
    }
  }
}

// 添加
const verCreate = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('version').insert(
    formData
  )
  console.log(data)
  if (data) {
    ctx.body = {
      success: 200,
      data: "success",
    }
  } else {
    ctx.body = {
      success: false
    }
  }
}

// 修改
const verUpdate = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('version')
    .where('id', formData.id)
    .update(formData)
  // console.log(data)
  if (data) {
    ctx.body = {
      success: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      success: false
    }
  }
}

// 删除
const verDelete = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('version')
    .where('id', formData.id).del()
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

const releases = async (ctx) => {
  console.log('ctx.query:', ctx.query)
  let formData = ctx.query
  let offset = (formData.currentPage - 1) * formData.pageSize
  let limit = formData.pageSize
  let keyword = formData.title

  limitdata = await sqlite3('version').count({ total: '*' })
  data = await sqlite3('version').orderBy('id', 'desc').select().limit(limit).offset(offset)
  total = limitdata[0].total
  console.log('pageSize:', formData.currentPage, 'currentPage:', limit)

  if (data) {
    ctx.body = {
      success: true,
      data: {
        list: data,
        total,
        pageSize: Number(limit),
        currentPage: Number(formData.currentPage)
      },
    }
  } else {
    ctx.body = {
      success: false
    }
  }
}
module.exports = { verList, verCreate, verUpdate, verDelete, releases }
